package com.woniu.shirocore;

import org.apache.shiro.authc.*;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.subject.PrincipalCollection;
import org.apache.shiro.authz.SimpleAuthorizationInfo;


import java.util.HashSet;
import java.util.Set;

/**
 * @author:陈涵
 * @Do:基于ini文件的自定义域
 * @date: 2022/9/5 16:54
 */
public class MyRealmDemo extends AuthorizingRealm {
    //把魔法值定义为变量
    private  final  String REALMNAME="MyRealmDemo";
    //授权，会抛出信息交给Shiro底层（SecurityManager）来帮忙控制逻辑
    //principals由认证方法中return对象SimpleAuthenticationInfo构造方法中定义的，不包含密码
    @Override
    protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principals) {
        //不建议直接使用魔法值，判断是否有下列的认证返回的输入传入
        if (principals.getRealmNames().contains(REALMNAME)) {
            //用于认证方法return中封装的数据，未来下面就直接封装token
            String username=principals.getPrimaryPrincipal()+"";
            //模拟数据库去角色表和权限表中查询数据出来，并封装到AuthorizationInfo里面
            Set<String> roles =new HashSet<>();//封装角色，数据库查出来封装到set里面就会去重
            roles.add("admin");
            roles.add("manager");
            roles.add("tourist");
            Set<String> perms=new HashSet<>();//封装权限
            perms.add("manager:add");
            perms.add("manager:edit");
            perms.add("manager:del");
            perms.add("manager:find");
            //封装
            SimpleAuthorizationInfo simpleAuthorizationInfo = new SimpleAuthorizationInfo();
            simpleAuthorizationInfo.setRoles(roles);
            simpleAuthorizationInfo.setStringPermissions(perms);
            return simpleAuthorizationInfo;
        }
        return null;
    }

    //认证流程的开发
    @Override
    protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken token) throws AuthenticationException {
        if (token instanceof UsernamePasswordToken) {
            UsernamePasswordToken usernamePasswordToken= (UsernamePasswordToken) token;
            String username=usernamePasswordToken.getUsername();
            //通过username去数据库查询数据，这里就模拟数据对象
            String password="123456";
            //判断登录的密码是否和传入的密码一致
            if(new String(usernamePasswordToken.getPassword()).equals(password)){
                System.out.println("登录成功");
                //SimpleAuthenticationInfo是AuthorizationInfo接口的实现类
                return new SimpleAuthenticationInfo(username,password,REALMNAME);
            }else {
                return  null;
            }
        }
        return null;
    }
}
